package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.PostDTO;
import com.yuelao.yuelao_backend.entity.Post;
import com.yuelao.yuelao_backend.entity.Topic;
import com.yuelao.yuelao_backend.entity.TopicMember;
import com.yuelao.yuelao_backend.mapper.PostMapper;
import com.yuelao.yuelao_backend.mapper.TopicMapper;
import com.yuelao.yuelao_backend.mapper.TopicMemberMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.PostService;
import com.yuelao.yuelao_backend.service.TopicService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 话题Service实现类
 */
@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic> implements TopicService {

    @Resource
    private PostMapper postMapper;
    
    @Resource
    private TopicMemberMapper topicMemberMapper;
    
    @Resource
    private PostService postService;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public List<Topic> getAllTopics() {
        LambdaQueryWrapper<Topic> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Topic::getPostCount)
               .orderByDesc(Topic::getMemberCount);
        return list(wrapper);
    }

    @Override
    public Topic getTopicDetail(Long topicId) {
        Topic topic = getById(topicId);
        if (topic == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "话题不存在");
        }
        return topic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTopic(String name, String description, String coverImage, Long createdBy) {
        // 检查话题名称是否已存在
        LambdaQueryWrapper<Topic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Topic::getName, name);
        Topic existing = getOne(wrapper);
        
        if (existing != null) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "话题名称已存在");
        }

        Topic topic = new Topic();
        topic.setName(name);
        topic.setDescription(description);
        topic.setCoverImage(coverImage);
        topic.setCreatedBy(createdBy);
        topic.setPostCount(0);
        topic.setMemberCount(0);
        topic.setViewCount(0);
        topic.setSortOrder(0);
        topic.setIsHot(false);
        topic.setStatus(1); // 默认状态为正常
        topic.setCreatedAt(LocalDateTime.now());
        topic.setUpdatedAt(LocalDateTime.now());
        
        return save(topic);
    }

    @Override
    public List<PostDTO> getTopicPosts(Long topicId, int page, int size) {
        // 验证话题存在
        Topic topic = getById(topicId);
        if (topic == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "话题不存在");
        }

        Page<Post> postPage = new Page<>(page, size);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Post::getTopicId, topicId)
               .eq(Post::getStatus, 1) // 正常状态
               .orderByDesc(Post::getCreatedAt);
        
        Page<Post> result = postMapper.selectPage(postPage, wrapper);
        
        return result.getRecords().stream()
                .map(postService::convertToPostDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean joinTopic(Long userId, Long topicId) {
        // 验证话题存在
        Topic topic = getById(topicId);
        if (topic == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "话题不存在");
        }

        // 检查是否已加入
        LambdaQueryWrapper<TopicMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TopicMember::getUserId, userId)
               .eq(TopicMember::getTopicId, topicId);
        TopicMember existing = topicMemberMapper.selectOne(wrapper);
        
        if (existing != null) {
            return true; // 已经加入
        }

        // 创建成员记录
        TopicMember member = new TopicMember();
        member.setUserId(userId);
        member.setTopicId(topicId);
        member.setJoinedAt(LocalDateTime.now());
        topicMemberMapper.insert(member);

        // 更新话题成员数
        topic.setMemberCount((topic.getMemberCount() != null ? topic.getMemberCount() : 0) + 1);
        topic.setUpdatedAt(LocalDateTime.now());
        updateById(topic);

        // 检查话题相关成就
        achievementService.checkTopicAchievements(userId);

        return true;
    }
}

